import { ref } from 'vue'
import { events } from './events'
export function useMenuDrop(containerRef, data) {

    // 移动的当前组件
    let currentComponent = ref(null)

    // 鼠标进入目标区域
    const dragenter = (event) => {
        const e = event || window.event
        e.dataTransfer.dropEffect = 'move'
    }

    // 鼠标经过目标区域
    const dragover = (event) => {
        const e = event || window.event
        e.preventDefault()
    }

    // 鼠标离开目标区域
    const dragleave = (event) => {
        const e = event || window.event
        e.dataTransfer.dropEffect = 'none'
    }

    // 松手事件
    const drop = (event) => {
        const e = event || window.event
        const blockList = data.value.blocks
        data.value = {
            ...data.value,
            blocks: [
                ...blockList,
                {
                    top: e.offsetY,
                    left: e.offsetX,
                    zIndex: 1,
                    key: currentComponent.value.key,
                    alignCenter: true,  // 拖拽完成之后，让鼠标位于元素的中间
                    props: {}
                }]
        }
        currentComponent.value = null
    }

    // 开始拖拽事件
    // eslint-disable-next-line no-unused-vars
    const dragstart = (component) => {
        // dragenter 进入目标元素中 添加一个移动的标识
        // dragover 在目标元素上经过时，阻止默认事件，否则不能触发drop
        // dragleave 离开元素时，添加一个禁用标识
        // drop 松手时，生成一个组件
        containerRef.value.addEventListener('dragenter', dragenter)
        containerRef.value.addEventListener('dragover', dragover)
        containerRef.value.addEventListener('dragleave', dragleave)
        containerRef.value.addEventListener('drop', drop)
        currentComponent.value = component
        events.emit('start')
    }

    // 拖拽结束-移除绑定事件
    const dragend = () => {
        containerRef.value.removeEventListener('dragenter', dragenter)
        containerRef.value.removeEventListener('dragover', dragover)
        containerRef.value.removeEventListener('dragleave', dragleave)
        containerRef.value.removeEventListener('drop', drop)
        events.emit('end')
    }

    return {
        dragstart,
        dragend
    }
}